import {defineStore} from 'pinia';
import {removeToken} from '@/utils/auth';
import {useCache} from '@/hooks/web/useCache';
import CacheKeys from '@/constants/CacheKeys';
import {loginApi} from '@/api/Api';
import userMockData from '@/store/MockData/userMockData';
import {UserInfoVO, UserVO} from '@/store/types';
import UserMockData from '@/store/MockData/userMockData';

const {wsCache} = useCache();

export const useUserStore = defineStore('admin-user', {
    state: (): UserInfoVO => ({
        user: UserMockData.user,
        roles: UserMockData.roles,
        permissions: UserMockData.permissions,
        menus: UserMockData.menus,
        isSetUser: true,
    }),
    getters: {
        getPermissions(): string[] {
            return this.permissions;
        },
        getRoles(): string[] {
            return this.roles;
        },
        getIsSetUser(): boolean {
            return this.isSetUser;
        },
        getUser(): UserVO {
            return this.user;
        },
    },
    actions: {
        // 登录时调用这个方法存储用户信息
        setUserInfo() {
            // TODO 从后端获取
            const userInfo = userMockData;
            this.permissions = userInfo.permissions;
            this.roles = userInfo.roles;
            this.user = userInfo.user;
            this.isSetUser = true;
            // 缓存用户信息
            wsCache.set(CacheKeys.USER_INFO, userInfo);
            // 缓存菜单信息
            wsCache.set(CacheKeys.USER_MENUS, userInfo.menus);
        },
        // 登出
        async loginOut() {
            removeToken();
            wsCache.clear();
            wsCache.deleteAllExpires();
            this.resetState();
        },
        // 重置数据
        resetState() {
            this.permissions = [];
            this.roles = [];
            this.isSetUser = false;
            this.user = {
                id: 0,
                avatar: '',
                nickname: '',
            };
        },
    },
});
